<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\lottery\api\controller;

use app\api\BaseController;
use app\api\model\User;
use app\api\model\Config;
use plugins\lottery\api\model\Lottery as LotteryModel;
/**
 * 抽奖
 */
class Lottery extends BaseController
{
    public $middleware = [
        "\app\api\middleware\AuthCheck" => ['only' => ['lottery','exchange','my']],
    ];
    
    /**
     * 列表显示
     */
    public function list()
    {
        if ($this->request->isPost()) {
            $input   = input('post.');
            $name = 'app_lottery';
            $data = Config::getVal($name);
            if (empty($data) || $data['status'] == 0) {
                return json(['status' => 'error','message' => '抽奖信息错误']);
            }
            $data['get'] = User::where('id', $this->request->userId)->value('now_integral');
            return json(['status' => 'success','message' => '获取成功', 'data' => $data]);
        }
    }
    
    /**
     * 开始抽奖
     */
    public function lottery() 
    {
        if ($this->request->isPost()) {
            $input   = input('post.');
            $name = 'app_lottery';
            $data = Config::getVal($name);
            if (empty($data) || $data['status'] == 0) {
                return json(['status' => 'error','message' => '抽奖信息错误']);
            }
            // 奖品
            $prize_arr = $data['prize'];
            foreach ($prize_arr as $key => $val) {
                // 其它奖品若没有开启或没有数量都会没权重
                if ($val['type'] !== 0) {
                    if ($val['number'] == 0 || $val['status'] == 0) {
                        $prize_arr[$key]['weight']  = 0;
                    }
                }
            }
            // 权重
            foreach($prize_arr as $key => $val) {
                $arr[] = $val['weight'];
            }
            $prize_key = '';
            //概率数组的总概率精度
            $proSum = array_sum($arr);
            //概率数组循环
            foreach($arr as $key => $proCur) {
                // 获取随机数
                $randNum = mt_rand(1, $proSum);
                if ($randNum <= $proCur) {
                    $prize_key = $key;
                    break;
                } else {
                    // 减掉当前中奖的概率
                    $proSum -= $proCur;
                }
            }
            $prize = $prize_arr[$prize_key];
            // 消耗积分(用户、日志记录)
            $user = User::find($this->request->userId);
            if ($user->now_integral < $data['number']) {
                return json(['status' => 'error','message' => '亲亲，您的积分不足哦']);
            }
            $user->now_integral = $user->now_integral - $data['number'];
            $user->save();
            // 减奖品数量
            $data['prize'][$prize_key]['number'] = $prize['number'] <= 0 ? 0 : $prize['number'] - 1;
            Config::setVal($name, '抽奖', $data);
            // 获得奖品
            $choose = empty($prize['prize'.$prize['type']]) ? 0 : $prize['prize'.$prize['type']];
            if ($prize['type'] === 1) {
                // 优惠券
                $status = 1;
                $exchange_time = time();
            }
            if ($prize['type'] === 2) {
                // 积分
                $status = 1;
                $exchange_time = time();
                $user = User::find($this->request->userId);
                $user->now_integral = $user->now_integral + $choose;
                $user->history_integral = $user->history_integral + $choose;
                $user->save();
            }
            if ($prize['type'] === 3) {
                // 商品实物
                $status = 0;
                $exchange_time = 0;
            }
            if ($prize['type'] === 4) {
                // 红包
                $status = 1;
                $exchange_time = time();
                $user = User::find($this->request->userId);
                $user->balance = $user->balance + $choose;
                $user->save();
            }
            if ($prize['type'] != 0) {
                LotteryModel::create([
                    'user_id'               => $this->request->userId,
                    'type'                  => $input['type'],
                    'lottery_title'         => $prize['title'],
                    'lottery_cover'         => $prize['cover'],
                    'lottery_type'          => $prize['type'],
                    'receiver_mobile'       => '',
                    'receiver_province'     => '',
                    'receiver_city'         => '',
                    'receiver_district'     => '',
                    'receiver_address'      => '',
                    'receiver_name'         => '',
                    'message'               => '',
                    'shipping_code'         => '',
                    'shipping_company_code' => '',
                    'create_time'           => time(),
                    'exchange_time'         => $exchange_time,
                    'status'                => $status,
                ]);
            }
            return json(['status' => 'success','message' => '抽奖成功', 'data' => $prize_key, 'prize' => $prize]);
        }
    }
    
    /**
     * 抽奖记录
     */
    public function record()
    {
        if ($this->request->isPost()) {
            $input   = input('post.');
            $where[] = ['type', '=', $input['type']];
            $data  = LotteryModel::where($where)->with(['user'])->order('create_time','desc')->page($input['page'],10)->select();
            $count = LotteryModel::where($where)->count();
            return json(['status' => 'success','message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
    
    /**
     * 商品兑换
     */
    public function exchange()
    {
        $input   = input('post.');
        $where[] = ['user_id', '=', $this->request->userId];
        $where[] = ['id', '=', $input['id']];
        $where[] = ['status', '=', 0];
        $where[] = ['lottery_type', '=', 3];
        $data  = LotteryModel::where($where)->find();
        if (empty($data)) {
            return json(['status' => 'success','message' => '奖品信息有误，无法填写']);
        }
        $data->receiver_mobile   = $input['mobile'];
        $data->receiver_province = $input['pcd'][0];
        $data->receiver_city     = $input['pcd'][1];
        $data->receiver_district = $input['pcd'][2];
        $data->receiver_address  = $input['address'];
        $data->receiver_name     = $input['consigner'];
        $data->exchange_time     = time();
        $data->status            = 1;
        $data->save();
        return json(['status' => 'success','message' => '兑换成功']);
    }
    
    /**
     * 我的中奖列表
     */
    public function my()
    {
        if ($this->request->isPost()) {
            $input   = input('post.');
            $where[] = ['user_id', '=', $this->request->userId];
            if (! empty($input['type'])) {
                $where[] = ['type', '=', $input['type']];
            }
            $data  = LotteryModel::where($where)->order('create_time','desc')->page($input['page'],10)->select();
            $count = LotteryModel::where($where)->count();
            return json(['status' => 'success','message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
}